import config from "config";
import { authHeader } from "../_helpers";
import dayjs from "dayjs";
var _ = require("lodash");
export const userService = {
  login,
  getCurrent,
  logout,
  getAll,
  update,
  register
};
function dateT(o) {
  var patt = /^\d{4,}\-(?:0?\d|1[12])\-(?:[012]?\d|3[01]) (?:[01]?\d|2[0-4]):(?:[0-5]?\d|60)$/;
  Object.keys(o).forEach((key, i) => {
    if (o[key] != null && patt.test(o[key])) {
      o[key] = new Date(o[key]);
    } else if (o[key] != null && typeof o[key] === "object") {
      dateT(o[key]);
    }
  });
}
function update(playload) {
  const body = Object.assign({}, playload.body);
  // 格式化时间
  body.birthday = dayjs(playload.body.birthday).format("YYYY-MM-DD HH:mm");
  const requestOptions = {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body)
  };
  console.log(playload);
  return fetch(`${config.apiUrl}/${playload.uri}`, requestOptions)
    .then(handleResponse)
    .then(reponse => {
      console.log(reponse);
      return reponse;
    });
}
function login(username, password) {
  const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ username, password })
  };

  return fetch(`${config.apiUrl}/auth/login`, requestOptions)
    .then(handleResponse)
    .then(user => {
      // login successful if there's a jwt token in the response
      if (user.token) {
        // store user details and jwt token in local storage to keep user logged in between page refreshes
        localStorage.setItem("auth-token", user.token);
      }

      return user;
    });
}
function register(user) {
  const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(user)
  };

  return fetch(`${config.apiUrl}/accounts`, requestOptions)
    .then(handleResponse)
    .then(user => {
      console.log("注册成功");
      console.log(user);
      return user;
    });
}

function getCurrent() {
  const requestOptions = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${localStorage.getItem("auth-token")}`
    },
    body: JSON.stringify({ token: localStorage.getItem("auth-token") })
  };

  return fetch(`${config.apiUrl}/auth/user`, requestOptions)
    .then(handleResponse)
    .then(user => {
      // login successful if there's a jwt token in the response
      if (user.token) {
        // store user details and jwt token in local storage to keep user logged in between page refreshes
        localStorage.setItem("auth-token", user.token);
      }
      //dateT(user);
      //user.user.privacy.birthday = new Date(user.user.privacy.birthday);
      return user;
    });
}

function logout() {
  // remove user from local storage to log user out
  localStorage.removeItem("auth-token");
}

function getAll() {
  const requestOptions = {
    method: "GET",
    headers: authHeader()
  };

  return fetch(`${config.apiUrl}/users`, requestOptions).then(handleResponse);
}

function handleResponse(response) {
  return response.text().then(text => {
    const data = text && JSON.parse(text);
    if (!response.ok) {
      if (response.status === 401) {
        alert("登录失败");
        // auto logout if 401 response returned from api
        logout();
        location.reload(true);
      }

      const error = (data && data.message) || response.statusText;
      return Promise.reject(error);
    }

    return data;
  });
}
